﻿using Microsoft.AspNetCore.Mvc.Filters;
using System;

namespace DotNetStar.TheKing.Web.Filters
{
    /// <summary>
    /// 只能是登录人自己的页面
    /// </summary>
    [AttributeUsage(AttributeTargets.Class)]
    public class OwnPageAttribute : Attribute, IPageFilter
    {
        public void OnPageHandlerExecuted(PageHandlerExecutedContext context) => Challenge(context);
        public void OnPageHandlerExecuting(PageHandlerExecutingContext context) => Challenge(context);
        public void OnPageHandlerSelected(PageHandlerSelectedContext context)
        => Challenge(context);

        private void Challenge(FilterContext context)
        {
            if (context.HttpContext.User.Identity.IsAuthenticated)
            {
                if(context.RouteData.Values.TryGetValue("userId",out var routeUserId) || context.HttpContext.Request.Query.TryGetValue("userId",out var uid))
                {
                    var currentUserId = context.HttpContext.User.Identity.UserId().ToString();
                    if (!routeUserId.ToString().Equals(currentUserId) && !uid.ToString().Equals(currentUserId))
                    {
                        context.HttpContext.Response.Redirect("/Unauthorize");
                        return;
                    }
                }
                return;
            }

            context.HttpContext.Response.Redirect("/Unauthorize");
            return;
        }
    }
}
